#!/usr/bin/env bash
# ------------------------------------
# default jvm args if you do not config in /jetty/boot.ini
# ------------------------------------
JVM_ARGS="-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=n,address=8412"
SERVICE_NAME="uranus-zma"
SERVICE_DIR="/root/fang/uranus-zma"
PID=$SERVICE_NAME\.pid

function init() {
    if [ -z "$LOG_PATH" ]; then
        LOG_PATH="/opt/logs/mobile"
    fi

    if [ -z "$WORK_PATH" ]; then
        WORK_PATH="$SERVICE_DIR/web/target"
    fi
    WEB_ROOT=$WORK_PATH/webroot
    cd $WORK_PATH
    mkdir webroot
    unzip -q *.war -d webroot
    mkdir -p $LOG_PATH

}

function run() {
    JAVA_CMD="java"
    cd $WEB_ROOT
    CLASSPATH=WEB-INF/classes
    for i in WEB-INF/lib/*
    do
        CLASSPATH=$CLASSPATH:$i
    done
    export CLASSPATH

    EXEC_JAVA="$JAVA_CMD $JVM_ARGS"
    nohup $EXEC_JAVA com.empress.uranus.zma.web.AppServiceApplication  > /dev/null 2>&1 &
    echo $! > $SERVICE_DIR/$PID
    echo "=== start $SERVICE_NAME"
}

# ------------------------------------
# actually work
# ------------------------------------
case "$1" in
    start)
            init
            run
            ;;
       stop)
        kill `cat $SERVICE_DIR/$PID`
        rm -rf $SERVICE_DIR/$PID
        echo "=== stop $SERVICE_NAME"

        sleep 5
		##
        P_ID=`ps -ef | grep -w "$SERVICE_NAME" | grep -v "grep" | awk '{print $2}'`
        if [ "$P_ID" == "" ]; then
            echo "=== $SERVICE_NAME process not exists or stop success"
        else
            echo "=== $SERVICE_NAME process pid is:$P_ID"
            echo "=== begin kill $SERVICE_NAME process, pid is:$P_ID"
            kill -9 $P_ID
        fi
        ;;

    restart)
        $0 stop
        sleep 2
        $0 start
        echo "=== restart $SERVICE_NAME"
        ;;

    *)
        ## restart
        $0 stop
        sleep 2
        $0 start
        ;;

esac
exit 0